from flask import render_template, Response, request, jsonify
import time
from camera.manager import generate_frames, capture_with_retry
from app.audio import TextToSpeech
from app.audio.recognize import SpeechRecognizer
import tempfile

# 创建TTS实例
tts = TextToSpeech()
# 创建语音识别实例（全局加载模型，避免重复加载）
speech_recognizer = SpeechRecognizer()

def init_routes(app):
    @app.route('/')
    def index():
        """首页"""
        return render_template('index.html')

    @app.route('/main')
    def main():
        """主页面"""
        return render_template('index.html')

    @app.route('/video/monitor')
    def video_monitor():
        """视频监控页面"""
        return render_template('video/monitor.html')

    @app.route('/video/capture')
    def video_capture():
        """视频拍照页面"""
        return render_template('video/capture.html')

    @app.route('/video/face')
    def video_face():
        """人脸识别页面"""
        return render_template('video/face.html')

    @app.route('/audio/monitor')
    def audio_monitor():
        """声音监控页面"""
        return render_template('audio/monitor.html')

    @app.route('/audio/wake')
    def audio_wake():
        """语音唤醒页面"""
        return render_template('audio/wake.html')

    @app.route('/audio/tts')
    def audio_tts():
        """语音合成页面"""
        return render_template('audio/tts.html')

    @app.route('/audio/test')
    def audio_test():
        """语音测试页面"""
        return render_template('audio/audio_test.html')

    @app.route('/audio/speak_test')
    def audio_speak_test():
        """语音识别测试页面"""
        return render_template('audio/speak_test.html')

    @app.route('/manage/archive')
    def manage_archive():
        """视频归档管理页面"""
        return render_template('manage/archive.html')

    @app.route('/manage/alert')
    def manage_alert():
        """报警设置页面"""
        return render_template('manage/alert.html')

    @app.route('/manage/user')
    def manage_user():
        """用户管理页面"""
        return render_template('manage/user.html')

    @app.route('/video_feed')
    def video_feed():
        """视频流路由"""
        return Response(
            generate_frames(),
            mimetype='multipart/x-mixed-replace; boundary=frame',
            headers={
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache',
                'Expires': '0',
                'Connection': 'keep-alive',
                'X-Accel-Buffering': 'no'  # 禁用 Nginx 缓冲
            }
        )

    @app.route('/api/tts', methods=['POST'])
    def text_to_speech():
        """文本转语音API"""
        try:
            data = request.get_json()
            text = data.get('text', '')
            voice_type = data.get('voice_type', 'female')
            speed = int(data.get('speed', 50))
            pitch = int(data.get('pitch', 50))
            volume = int(data.get('volume', 80))
            
            success, message = tts.speak(text, voice_type, speed, pitch, volume)
            
            if success:
                return jsonify({'message': message}), 200
            else:
                return jsonify({'error': message}), 400
                
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/tts/history', methods=['GET'])
    def get_tts_history():
        """获取语音合成历史"""
        try:
            limit = request.args.get('limit', 10, type=int)
            history = tts.get_history(limit)
            return jsonify(history), 200
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/speech_recognize', methods=['POST'])
    def api_speech_recognize():
        """语音识别API，支持录音和文件上传"""
        try:
            if 'audio' not in request.files:
                return jsonify({'error': '未上传音频文件'}), 400
            audio_file = request.files['audio']
            with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp:
                audio_file.save(tmp.name)
                tmp.flush()
                text = speech_recognizer.recognize(tmp.name)
            return jsonify({'text': text}), 200
        except Exception as e:
            return jsonify({'error': str(e)}), 500